package com.servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.dao.GuestBookDAO;
import com.guestbook.dao.impl.GuestBookDAOJdbc;
import com.guestbook.javabeans.GuestBook;
import com.tools.StringUtil;

public class AddMessageServlet extends HttpServlet {

	private static final long serialVersionUID = -8133081170616605646L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		boolean result=false;
		String name = request.getParameter("name");
		String title = request.getParameter("title");
		String msg="";
		if (StringUtil.validateIsNull(name)) {
			msg="对不起，姓名不能为空，请重新输入！<br>";
		} else if (StringUtil.validateIsNull(title)) {
			msg="对不起，主题不能为空，请重新输入！<br>";
		} else {
				GuestBook gb=new GuestBook();
				GuestBookDAO dao=new GuestBookDAOJdbc();
				gb.setName(StringUtil.filterHtml(name));
				gb.setTitle(StringUtil.filterHtml(title));
				gb.setEmail(StringUtil.filterHtml(request.getParameter("email")));
				gb.setPhone(StringUtil.filterHtml(request.getParameter("phone")));
				gb.setContent(request.getParameter("content"));
				SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
				gb.setTime(sdf.format(new java.util.Date()));
				result=dao.save(gb);
			if (result) {
				msg="恭喜你，留言添加成功！<br>";
			} else {
				msg="对不起，留言添加不成功，请重新输入！<br>";
			}
			request.setAttribute("msg", msg);
			request.getRequestDispatcher("/addResult.jsp").forward(request, response);
		}
	}

}
